package com.github.browep.bat.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.github.browep.bat.Constants;
import com.github.browep.bat.R;
import com.github.browep.bat.ScreenService;
import com.github.browep.bat.util.PunchCardUtils;
import org.w3c.dom.Element;

import java.util.List;

import static com.github.browep.bat.util.UiUtilities.findAllByTag;
import static com.github.browep.bat.util.XmlUtil.getChildElementListWithTag;
import static com.github.browep.bat.util.XmlUtil.getElementByTagName;

public class Home extends BaseActivity
{

    private TextView punchTextView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ViewGroup view = (ViewGroup) setupWrappedUI(R.layout.home);

        ScreenService.Screen screen = getScreenService().getScreenById("home");

        // get all the tiles
        List<Element> tilesElems = getChildElementListWithTag(getElementByTagName(screen.getScreenElement(), "tiles"), "tile");

        for(Element tileElem : tilesElems){
            List<View> buttons = findAllByTag(view,tileElem.getAttribute("tag"));
            for(View button : buttons){
                ((Button)button).setText(getElementByTagName(tileElem,"text").getTextContent());
                button.setOnClickListener(onClickListenerFromElem(getElementByTagName(tileElem,"on-click")));

            }
        }

        punchTextView = (TextView) findViewById(R.id.home_text);
        updateUI();

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateUI();
            }
        }, new IntentFilter(Constants.CARD_PUNCHED_INTENT));

    }

    private void updateUI() {
        punchTextView.setText("Punches: " + PunchCardUtils.getCurrentPunches(this));
    }
}
